package com.keter.common.exp;

import com.keter.framework.web.util.DownloadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

/**
 * Created by gulx@neusoft.com on 2020/10/2.
 */
@RestController
@RequestMapping("/download")
public class DownloadController {
    private static final Logger logger = LoggerFactory.getLogger(DownloadController.class);

    // http://127.0.0.1:9990/download/1?localFileUri=e:/temp.yaml
    @GetMapping("/1")
    public void makeDownload1(HttpServletRequest request,
                                    HttpServletResponse response, String localFileUri) throws IOException {
        logger.info("method1 begin");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment; filename=haha");
		toDownload(response, localFileUri);
    }

    // http://127.0.0.1:9990/download/2?localFileUri=e:/temp.yaml
    @GetMapping("/2")
    public void makeDownload2(HttpServletRequest request,
                                    HttpServletResponse response, String localFileUri) throws IOException {
        DownloadUtil.makeDownload(request,response,new File(localFileUri));
    }

    private static void toDownload(HttpServletResponse response, String localFileUri) throws IOException {
        logger.info("stream begin");
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(localFileUri));
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        try {
            byte[] buff = new byte[512];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            logger.info("stream end");
        } catch (IOException e) {
           e.printStackTrace();
        } finally{
            bis.close();
            bos.close();
        }
    }
}
